<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-cascades"></i> 该页面已完成
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-input
          v-model="query.name"
          clearable
          placeholder="名称"
          class="handle-input mr10"
          @keyup.native.enter="handleSearch()"
        ></el-input>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button
          type="primary"
          @click="handleAdd"
          v-if="srPermissions.includes('sys:role:save')"
          >新增</el-button
        >
        <el-button
          type="danger"
          class="handle-del"
          @click="delAllSelection"
          v-if="srPermissions.includes('sys:role:delete')"
          >删除</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelectionChange"
        @sort-change="sortChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="name"
          label="名称"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="remark"
          label="备注"
          align="center"
        ></el-table-column>

        <el-table-column
          prop="createDate"
          label="创建时间"
          sortable
          align="center"
        ></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleEdit(scope.$index, scope.row)"
              v-if="srPermissions.includes('sys:role:update')"
              >编辑</el-button
            >
            <el-button
              type="text"
              class="red"
              @click="handleDelete(scope.$index, scope.row)"
              v-if="srPermissions.includes('sys:role:delete')"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total,sizes, prev, pager, next, jumper"
          :page-sizes="[5, 10, 20, 30]"
          @size-change="handleSizeChange"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 新增弹出框 -->
    <el-dialog title="新增" :visible.sync="addVisible" width="50%">
      <el-form :model="addRuleForm" label-width="auto" :rules="rules">
        <el-form-item label="名称" prop="name">
          <el-input clearable v-model="addRuleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input clearable v-model="addRuleForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <el-form :model="addRuleForm" label-width="auto" :rules="rules">
        <el-form-item label="菜单授权" prop="menuAuthorizeList">
          <el-tree
            accordion
            :data="addRuleForm.menuAuthorizeList"
            show-checkbox
            node-key="id"
            ref="tree"
            highlight-current
            :props="defaultProps"
          >
          </el-tree>
        </el-form-item>

        <el-form-item label="数据授权" prop="dataAuthorizeList">
          <el-tree
            accordion
            :data="addRuleForm.dataAuthorizeList"
            show-checkbox
            node-key="id"
            ref="menuListTree"
            highlight-current
            :props="defaultProps"
            @check-change="handleCheckChange"
          >
          </el-tree>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAdd">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑弹出框-->
    <el-dialog title="编辑" :visible.sync="editVisible" width="50%">
      <el-form ref="editForm" :model="editForm" label-width="auto">
        <el-form-item label="名称">
          <el-input clearable v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input clearable v-model="editForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <!-- 共用 addRuleForm中数据 便于初始化一些数据-->
      <el-form :model="addRuleForm" label-width="auto" :rules="rules">
        <el-form-item label="菜单授权" prop="menuAuthorizeList">
          <el-tree
            accordion
            :data="addRuleForm.menuAuthorizeList"
            show-checkbox
            node-key="id"
            ref="tree"
            highlight-current
            :props="defaultProps"
            :default-checked-keys="menuAuthorizeSelectChecked"
          >
          </el-tree>
        </el-form-item>
        <el-form-item label="数据授权" prop="dataAuthorizeList">
          <el-tree
            accordion
            :data="addRuleForm.dataAuthorizeList"
            show-checkbox
            node-key="id"
            ref="menuListTree"
            highlight-current
            :props="defaultProps"
            @check-change="handleCheckChange"
            :default-checked-keys="dataAuthorizeSelectChecked"
          >
          </el-tree>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import { sysRoleMixin } from "common/js/userManage";
import util from "utils/util";
import { mapGetters } from "vuex";
// console.log(sysRoleMixin);
export default {
  name: "sysrole",
  // mixins: [sysRoleMixin],
  data() {
    return {
      srPermissions: [],
      tempKey: -666666,
      defaultProps: {
        children: "children",
        label: "label",
      },
      query: {
        order: "",
        orderField: "",
        pageIndex: 1,
        pageSize: 20,
        name: "",
      },
      tableData: [
        {
          id: "",
          name: "",
          remark: "",
          createDate: "",
          menuIdList: null,
          deptIdList: null,
        },
      ],

      addRuleForm: {
        name: "",
        remark: "",
        // 菜单授权
        menuAuthorizeList: [
          {
            id: "",
            label: "",
            children: [],
          },
        ],
        // 数据授权
        dataAuthorizeList: [
          {
            id: "",
            label: "",
            children: [],
          },
        ],
        dataAuthorizeIdList: [],
        menuAuthorizeIdList: [],
      },
      rules: {
        name: [{ required: true, message: "必填不能为空", trigger: "blur" }],
        menuAuthorizeList: [],
        dataAuthorizeList: [],
      },
      multipleSelection: [],
      delList: [],
      editVisible: false,
      addVisible: false,
      pageTotal: 0,
      editForm: {
        id: "",
        name: "",
        remark: "",
      },
      menuAuthorizeSelectChecked: [], // 菜单授权
      dataAuthorizeSelectChecked: [], // 数据授权,
      idx: -1,
      ids: [],
      // newArr: [],
      array: [],
      // deleteId: []
    };
  },

  created() {
    this.getSysRoleData({});
    this.srPermissions = this.permissions;
  },
  computed: {
    ...mapGetters(["permissions"]),
  },
  watch: {
    "$route.path": function(newVal, oldVal) {
      if (newVal == "/sys-role") {
        this.srPermissions = this.permissions;
      }
    },
    // 刷新浏览器时触发
    permissions: function(newVal, oldVal) {
      // console.log(newVal, oldVal);
      this.srPermissions = newVal;
    },
  },
  methods: {
    // 获取数据
    getSysRoleData({
      order = this.query.order,
      orderField = this.query.orderField,
      page = this.query.pageIndex,
      limit = this.query.pageSize,
      name = this.query.name,
      _t = Date.now(),
    }) {
      this.$axios
        .get("/sys/role/page", {
          params: {
            order,
            orderField,
            page,
            limit,
            name,
            _t,
          },
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }
          this.pageTotal = res.data.total || 0;
          this.tableData = res.data.list;
          this.tableData.map((item) => {
            item.createDate = this.dateFormat(item.createDate);
          });
        })
        .catch(() => {});
    },
    // 表头排序
    sortChange({ column, prop, order }) {
      prop = prop === "createDate" ? "create_date" : prop;
      this.$set(this.query, "orderField", prop);
      if (order === "ascending") {
        this.$set(this.query, "order", order.substr(0, 3));
        this.getSysRoleData({});
      } else if (order === "descending") {
        this.$set(this.query, "order", order.substr(0, 4));
        this.getSysRoleData({});
      }
    },
    // 编辑操作
    handleEdit(index, row) {
      this.idx = index;
      // console.log(index, row);
      this.editForm = row;
      this.editVisible = true;

      this.addRuleForm.dataAuthorizeIdList = [];
      this.addRuleForm.menuAuthorizeIdList = [];
      // 初始化菜单授权
      this.initMenuAuthorize(index, row);
      // 初始化数据授权
      this.initDataAuthorize();
    },
    // 初始化菜单授权
    initMenuAuthorize(index, row) {
      this.$axios
        .get("/sys/menu/select", {
          params: { _t: Date.now() },
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }
          this.addLableAttribute(res.data);
          this.addRuleForm.menuAuthorizeList = res.data;

          // 正确渲染菜单授权
          this.reanderMenuAuthor(index, row);
        })
        .catch(() => {});
    },
    reanderMenuAuthor(index, row) {
      this.menuAuthorizeSelectChecked = [];
      // 获取当前用户信息 正确显示菜单授权
      this.$axios
        .get("/sys/role/" + row.id, {
          params: {
            _t: Date.now(),
          },
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }
          // 数据授权
          this.dataAuthorizeSelectChecked = res.data.deptIdList;
          // 菜单授权
          var menuAuthorizeList = this.addRuleForm.menuAuthorizeList;
          console.log(menuAuthorizeList);
          var son = [];
          menuAuthorizeList.map((grandItem) => {
            if (grandItem.children && grandItem.children.length) {
              grandItem.children.map((fatherItem) => {
                if (fatherItem.children && fatherItem.children.length) {
                  fatherItem.children.map((subItem) => {
                    son.push(subItem.id);
                  });
                }
              });
            }
          });
          var fatherId = [];
          menuAuthorizeList.map((grandItem) => {
            if (grandItem.children && grandItem.children.length) {
              grandItem.children.map((fatherItem) => {
                fatherId.push(fatherItem.id);
              });
            }
          });
          var grandId = [];
          menuAuthorizeList.map((item) => {
            grandId.push(item.id);
          });

          var menuIdList = res.data.menuIdList; // 包含了父亲和爷爷id 需要处理
          console.log("未处理前", menuIdList);
          var tempObj = {};
          var originObj = {};
          for (var i = 0; i < menuIdList.length; i++) {
            for (var j = 0; j < grandId.length; j++) {
              if (menuIdList[i] == grandId[j]) {
                originObj[menuIdList[i]] = {};
                tempObj[menuIdList[i]] = {};
              }
            }
          }
          console.log(tempObj, originObj);
          // 此时tempObj结构 { 'grandId': {}, ... }

          menuAuthorizeList.map((grandItem) => {
            for (var k in tempObj) {
              if (grandItem.id == k) {
                if (grandItem.children && grandItem.children.length) {
                  grandItem.children.map((fatherItem) => {
                    originObj[k][fatherItem.id] = [];
                    for (var i = 0; i < menuIdList.length; i++) {
                      if (menuIdList[i] == fatherItem.id) {
                        tempObj[k][menuIdList[i]] = [];
                      }
                    }
                  });
                }
              }
            }
          });
          // console.log(tempObj, originObj);
          // 此时tempObj 结构为 { 'grandId': { 'fatherId': [] }, ... }

          menuAuthorizeList.map((grandItem) => {
            for (var k in tempObj) {
              if (grandItem.id == k) {
                if (grandItem.children && grandItem.children.length) {
                  grandItem.children.map((fatherItem) => {
                    for (var i = 0; i < menuIdList.length; i++) {
                      // originObj[k][menuIdList[i]].push(subItem.id);
                      if (menuIdList[i] == fatherItem.id) {
                        if (fatherItem.children && fatherItem.children.length) {
                          fatherItem.children.map((subItem) => {
                            // originObj[k][fatherItem.id].push(subItem.id);
                            for (var j = 0; j < menuIdList.length; j++) {
                              if (menuIdList[j] == subItem.id) {
                                tempObj[k][fatherItem.id].push(menuIdList[j]);
                              }
                            }
                          });
                        }
                      }

                      if (fatherItem.children && fatherItem.children.length) {
                        fatherItem.children.map((subItem) => {
                          // console.log(subItem);
                          originObj[k][fatherItem.id].push(subItem.id);
                        });
                      }
                    }
                  });
                }
              }
            }
          });
          for (var k in originObj) {
            for (var key in originObj[k]) {
              originObj[k][key] = [...new Set(originObj[k][key])];
            }
          }
          console.log(tempObj, originObj);

          for (var k in tempObj) {
            // var { k } = originObj;
            for (var m in tempObj[k]) {
              var len = tempObj[k][m].length;
              if (len < originObj[k][m].length) {
                if (menuIdList.includes(m)) {
                  menuIdList.splice(menuIdList.indexOf(m), 1); // 删除fatherId
                }

                // 此时还要删除grandId
                if (menuIdList.includes(k)) {
                  menuIdList.splice(menuIdList.indexOf(k), 1);
                }
              }
            }

            var fatherLen = Object.keys(tempObj[k]).length;
            if (fatherLen < Object.keys(originObj[k]).length) {
              if (menuIdList.includes(k)) {
                menuIdList.splice(menuIdList.indexOf(k), 1); // 删除grandId
              }
            }
          }
          // 菜单授权
          this.menuAuthorizeSelectChecked = menuIdList;
          console.log("处理后", this.menuAuthorizeSelectChecked);
        })
        .catch(() => {});
    },
    // 保存编辑
    saveEdit() {
      let parentArr = this.$refs.tree.getHalfCheckedKeys(); //获取半选中状态的id
      let childArr = this.$refs.tree.getCheckedKeys(); //获取全选中的id

      this.addRuleForm.menuAuthorizeIdList = parentArr.concat(childArr); //拼接在一起
      console.log(this.addRuleForm.menuAuthorizeIdList);

      let parentArr1 = this.$refs.menuListTree.getHalfCheckedKeys();
      let childArr1 = this.$refs.menuListTree.getCheckedKeys(); //获取全选中的id
      this.addRuleForm.dataAuthorizeIdList = parentArr1.concat(childArr1); //拼接在一起

      // 得到成功提示
      this.$axios
        .put("/sys/role", {
          id: this.editForm.id,
          name: this.editForm.name,
          menuIdList: this.addRuleForm.menuAuthorizeIdList,
          deptIdList: this.addRuleForm.dataAuthorizeIdList,
          remark: this.editForm.remark,
          createDate: null,
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }
          this.$message.success(`修改第 ${this.idx + 1} 行成功`);
          this.getSysRoleData({});
          // this.newArr = [];
          this.editVisible = false;
        })
        .catch(() => {});
    },
    // 选择数据授权
    handleCheckChange(data, checked, indeterminate) {
      // console.log("数据授权", data, checked, indeterminate);
      if (checked) {
        this.initDataAuthorizeIdList(data);
      } else if (checked == false) {
        if (this.array.includes(data.id) && data.children.length == 0) {
          this.array.splice(this.array.indexOf(data.id), 1);
        } else if (this.array.includes(data.id) && data.children.length != 0) {
          this.array.splice(this.array.indexOf(data.id), 1);
          data.children.map((item) => {
            this.array.splice(this.array.indexOf(item.id), 1);
          });
        }
      }
      // console.log("数据授权", this.array);
    },

    // 分页导航
    handlePageChange(val) {
      this.$set(this.query, "pageIndex", val);
      this.getSysRoleData({});
    },
    handleSizeChange(val) {
      this.$set(this.query, "pageSize", val);
      this.getSysRoleData({});
    },
    initDataAuthorizeIdList(params) {
      var _this = this;
      _this.array.push(params.id);
      if (params.pid != "0") {
        _this.array.push(params.id, params.pid);
      }
      var grandId = "";

      // 选了三级 或 二级
      this.addRuleForm.dataAuthorizeList.map((item) => {
        if (item.id == params.pid && item.pid != 0) {
          grandId = item.pid;
        } else {
          for (var i = 0; i < item.children.length; i++) {
            if (item.children[i].id == params.pid) {
              grandId = item.children[i].pid;
            }
          }
        }
      });

      if (grandId != "") {
        _this.array.push(grandId);
      }

      function myMap(arr) {
        arr = Array.from(arr);
        if (arr.length) {
          for (var item of arr) {
            _this.array.push(item.id, item.pid);
            if (item.children && item.children.length) {
              return myMap(item.children);
            }
          }
        }
      }

      myMap(params.children);

      _this.array = [...new Set(_this.array)];

      _this.addRuleForm.dataAuthorizeIdList = _this.array;
      // return _this.array;
    },

    initDataAuthorize() {
      this.$axios
        .get("/sys/dept/list", {
          params: { _t: Date.now() },
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }
          this.addLableAttribute(res.data);
          this.addRuleForm.dataAuthorizeList = res.data;
        })
        .catch(() => {});
    },

    // 递归:添加label属性
    addLableAttribute(array) {
      array.map((item) => {
        if (!item.children || (item.children && item.children.length === 0)) {
          item.label = item.name;
        } else {
          if (item.children && item.children.length) {
            item.label = item.name;
            this.addLableAttribute(item.children);
          }
        }
      });
    },
    // 新增
    handleAdd() {
      this.addVisible = true;
      this.addRuleForm.menuAuthorizeIdList = [];
      this.addRuleForm.dataAuthorizeIdList = [];
      // 初始化菜单授权
      this.initMenuAuthorize();
      // 初始化数据授权
      this.initDataAuthorize();
    },
    saveAdd() {
      let parentArr = this.$refs.tree.getHalfCheckedKeys(); //获取半选中状态的id
      let childArr = this.$refs.tree.getCheckedKeys(); //获取全选中的id
      this.addRuleForm.menuAuthorizeIdList = parentArr.concat(childArr); //拼接在一起

      let parentArr1 = this.$refs.menuListTree.getHalfCheckedKeys();
      let childArr1 = this.$refs.menuListTree.getCheckedKeys(); //获取全选中的id
      this.addRuleForm.dataAuthorizeIdList = parentArr1.concat(childArr1); //拼接在一起

      // 得到成功提示
      this.$axios
        .post("/sys/role", {
          name: this.addRuleForm.name,
          menuIdList: this.addRuleForm.menuAuthorizeIdList, // ['id', 'id']
          deptIdList: this.addRuleForm.dataAuthorizeIdList, // ['id', 'id']
          remark: this.addRuleForm.remark,
        })
        .then(({ data: res }) => {
          this.$message.success("操作成功");
          this.addVisible = false;
          this.addRuleForm = {
            name: "",
            remark: "",
            // 菜单授权
            menuAuthorizeList: [
              {
                id: "",
                label: "",
                children: [],
              },
            ],
            // 数据授权
            dataAuthorizeList: [
              {
                id: "",
                label: "",
                children: [],
              },
            ],
            dataAuthorizeIdList: [],
            menuAuthorizeIdList: [],
          };
          this.getSysRoleData({});
        })
        .catch(() => {});
    },
    // 触发搜索按钮
    handleSearch() {
      this.$set(this.query, "pageIndex", 1);
      var params = {
        order: this.query.order,
        orderField: this.query.orderField,
        page: this.query.pageIndex,
        limit: this.query.pageSize,
        name: this.query.name,
        _t: Date.now(),
      };
      this.tableData = [];
      this.getSysRoleData(params);
    },
    // 删除操作
    handleDelete(index, row) {
      this.ids[0] = row.id;
      util.delete.call(this, "/sys/role", index, this.ids, this.getSysRoleData);
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    delAllSelection() {
      var ids = this.multipleSelection.map((item) => {
        return item.id;
      });
      util.delete.call(this, "/sys/role", "", ids, this.getSysRoleData);
    },
  },
};
</script>

<style scoped>
@import "../../common/css/index.css";
</style>
